package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.HttpUtil;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Member;
import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    public static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 1.调用微信接口服务，获得当前微信openid
        String openid = getOpenid(userLoginDTO.getCode());
        // 2.对象openid进行合法性判断
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        // 3.判断当前用户是否为新用户
        User user = userMapper.getByOpenId(openid); // 调用UserMapper接口查询用户
        if (user == null) {
            // 当前用户是新用户，自动完成注册，调用usermapper接口插入到数据库user表中
            // 4.新用户用于注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            // 调用新增接口
            userMapper.insert(user);
        }
        // 5.返回用户信息
        return user;
    }

    /*调用微信接口获取openid
     * @param code:是微信用户的临时凭证
     * */
    private String getOpenid(String code) {
        HashMap<String, String> hashMap = new HashMap<>();
        // 创建请求参数map对象
        hashMap.put("appid", weChatProperties.getAppid());
        hashMap.put("secret", weChatProperties.getSecret());
        hashMap.put("js_code", code);
        hashMap.put("grant_type", "authorization_code");
        // 请求微信接口
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, hashMap);
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
}
